package com.huafv.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huafv.reggie.common.R;
import com.huafv.reggie.entity.Employee;
import com.huafv.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        HttpSession session = request.getSession();

        // 将密码进行Md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 通过用户名查询用户信息
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(employeeLambdaQueryWrapper);

        if (ObjectUtils.isEmpty(one)) {
            // 账户名错误
            return R.error("登录失败，账号或密码错误");
        }

        // 比对加密后的密码
        if (!one.getPassword().equals(password)) {
            // 密码错误
            return R.error("登录失败，账号或密码错误");
        }

        if (one.getStatus() == 0) {
            // 用户状态
            return R.error("账号已被禁用，请联系客服处理");
        }

        session.setAttribute("employee", one.getId());
        one.setPassword("NULL");

        return R.success(one);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {

        // 移除Session缓存
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        log.info("新增员工，员工信息{}", employee);

        // 设置初始密码
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);

        // 设置创建时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        // 设置创建人
//        Long employeeId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(employeeId);
//        employee.setUpdateUser(employeeId);

        employeeService.save(employee);

        return R.success("新增员工成功");
    }

    /**
     * @param page     第几页
     * @param pageSize 页记录数据
     * @param name     员工姓名
     * @return Page
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(int page, int pageSize, String name) {
        log.info("Page = {}, pageSize = {}, name = {}", page, pageSize, name);
        // 新建Page对象
        Page<Employee> employeePage = new Page<>(page, pageSize);

        // 构建模糊查询对象
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);

        // 执行查询
        employeeService.page(employeePage, lambdaQueryWrapper);

        // 返回结果
        return R.success(employeePage);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        log.info(employee.toString());

//        employee.setUpdateUser((Long) httpServletRequest.getSession().getAttribute("employee"));
//        employee.setUpdateTime(LocalDateTime.now());
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");
    }

    /**\
     * 根据Id查询员工信息
     * @param id 员工Id
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据id:{}查询员工信息", id);
        Employee employee = employeeService.getById(id);
        if(ObjectUtils.isEmpty(employee)){
            return R.error("查询不到用户信息");
        }
        return R.success(employee);
    }
}
